package com.qq.BFMRSE.frame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import net.sf.json.JSONArray;
import com.qq.BFMRSE.extractWord.SelectWord;
import com.qq.BFMRSE.extractWord.wordTFAndIDFInfo;
import com.qq.BFMRSE.index.buildIndex;
import com.qq.BFMRSE.requestModule.downFilesModule;
import com.qq.BFMRSE.requestModule.searchWordModule;
import com.qq.BFMRSE.serialize.objectSerializeUtil;
import com.qq.BFMRSE.trapDoor.GenTropDoor;
import com.qq.BFMRSE.util.BFConstants;
public class searchFrame extends JFrame implements ActionListener,MouseListener{
    private SelectWord selectWord;
	private JTextField searchInput;
	private JButton btnSearch;
    private JButton btnDownLoad;
    private JLabel pathLabel;
    private JTextField filePathTextF;
    private JButton btnFileChose;
	private JList list ;
	private List<CheckListItem> dataList ;
	private DefaultListModel model ;
	private JFileChooser jfc;
	private int first;
	private int sec;
	private String userName;//用户名
	public JTextField getSearchInput(){
		return searchInput;
	}
	public searchFrame(String userName) {
		try {
			selectWord=(SelectWord) objectSerializeUtil.deserialize( BFConstants.WORDINFOFILE+File.separator+BFConstants.INITKEYVALUE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.userName=userName;
		this.setResizable(false);
		this.setSize(500, 300);
        this.setTitle("BFMRSE搜索界面");
        ImageIcon imgBF=new ImageIcon("images\\BFMRSE.png");
        this.setIconImage(imgBF.getImage()); 
        this.setLocationRelativeTo(null);
        jfc=new JFileChooser();
        jfc.setCurrentDirectory(new File("d://"));// 文件选择器的初始目录定为d盘
        searchInput=new JTextField();
        btnSearch=new JButton("搜索");
        btnDownLoad=new JButton("下载所选择的文件");
        filePathTextF=new JTextField();
        btnFileChose=new JButton("选择文件存储位置");
        btnSearch.addActionListener(this);
        searchInput.setColumns(10);
        JPanel jpTop=new JPanel();
        jpTop.setLayout(new BoxLayout(jpTop, BoxLayout.X_AXIS));
        jpTop.add(searchInput);
        jpTop.add(btnSearch);
		this.getContentPane().add(jpTop, BorderLayout.NORTH);
		JPanel jpFileChose=new JPanel();
		filePathTextF.setColumns(10);
		pathLabel=new JLabel("位置:");
		jpFileChose.add(pathLabel);
		jpFileChose.add(filePathTextF);
		jpFileChose.add(btnFileChose);
		jpFileChose.add(btnDownLoad);
		btnFileChose.addActionListener(this);
		btnDownLoad.addActionListener(this);
		getContentPane().add(jpFileChose,BorderLayout.SOUTH);
		dataList=new ArrayList<>();
        list = new JList();
        list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        list.setListData(dataList.toArray());
        list.setCellRenderer(new CheckListRenderer());
        list.setSelectionBackground(new Color(177,232,58));
        list.setSelectionForeground(Color.black);
        list.addMouseListener(this);
        getContentPane().add(new JScrollPane(list),BorderLayout.CENTER);
       
	}
	public static void main(String []args){
		searchFrame sf=new searchFrame("qiong");
		sf.setVisible(true);
	}
	
	class CheckListItem {
	    private String label;
	    private boolean isSelected = false;
	    public CheckListItem(String label) {
	        this.label = label;
	    }
	    public boolean isSelected() {
	        return isSelected;
	    }
	    public void setSelected(boolean isSelected) {
	        this.isSelected = isSelected;
	    }
	    public String toString() {
	        return label;
	    }
	}
	// Handles rendering cells in the list using a check box
	class CheckListRenderer extends JCheckBox implements ListCellRenderer {
	    public Component getListCellRendererComponent(JList list, Object value,
	            int index, boolean isSelected, boolean hasFocus) {
	        setEnabled(list.isEnabled());
	        setSelected(((CheckListItem) value).isSelected());
	        setFont(list.getFont());
	        if (isSelected) {
	            this.setBackground(list.getSelectionBackground());
	            this.setForeground(list.getSelectionForeground());
	        } else {
	            this.setBackground(list.getBackground());
	            this.setForeground(list.getForeground());
	        }
	        setText(value.toString());
	        return this;
	    }
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		//处理搜索请求
		if(e.getSource()==btnSearch){
			String words=searchInput.getText();
			if("".equals(words)){
				JOptionPane.showMessageDialog(this, "请求的关键词为空！",
						"提示",JOptionPane.INFORMATION_MESSAGE);
			}else {
			  String []wordSet=words.split(BFConstants.WORDSPILTB);
			  int K=-1;
			  Pattern digpattern = Pattern.compile("[0-9]*"); 
			  Matcher digMatcher=digpattern.matcher(wordSet[wordSet.length-1]);
			  if(digMatcher.matches()){
				  K=Integer.parseInt(wordSet[wordSet.length-1]);
			  }
			  List<String>searchWordList=new ArrayList<>();
			  int n=wordSet.length;
			  if(K!=-1){
				  n=n-1;
			  }
			  for(int i=0;i<n;i++){
				  if(wordTFAndIDFInfo.idfMap.keySet().contains(wordSet[i])){
					  searchWordList.add(wordSet[i]);
					  System.out.println("有效关键字："+wordSet[i]);
				  }
				  //最后一个关键字
				  
			  }
			  if(searchWordList.size()==0){
					JOptionPane.showMessageDialog(this, "输入的关键字全部无效！",
							"提示",JOptionPane.INFORMATION_MESSAGE);
			  }else {
				  buildIndex buIndex=new buildIndex(selectWord.getSkPath());
				  GenTropDoor genTropDoor=new GenTropDoor(buIndex.getInSk());
				  searchWordModule searchModule=new searchWordModule(genTropDoor);
				  String searchURL=BFConstants.URL+BFConstants.URLSPE+BFConstants.SEARCH;
				  String searchResult=searchModule.search(searchURL, searchWordList, userName,K);
				  JSONArray jArray=JSONArray.fromObject(searchResult);
				  List<String>searchList=jArray.toList(jArray);
				  dataList.clear();
				  Iterator<String>iterator=searchList.iterator();
				  while (iterator.hasNext()) {
					dataList.add(new CheckListItem(iterator.next()));
				}
				  list.setListData(dataList.toArray());
	  	          list.validate();//更新Jlist
				  
				
			}
//			  dataList.add(new CheckListItem("a3.txt"));
//			  list.setListData(dataList.toArray());
//  	          list.validate();//更新Jlist
			}
		}else if(e.getSource()==btnFileChose){
			//响应选择下载文件夹选择操作
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设置只能选择文件夹
			int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
			if (state == 1) {
				return;// 撤销则返回
			} else {
				File downLoadFilePath=jfc.getSelectedFile();
				filePathTextF.setText(downLoadFilePath.getAbsolutePath());
			}
		}else if(e.getSource()==btnDownLoad){
			//响应下载操作
			String filePath=filePathTextF.getText();
			if("".equals(filePath)){
				JOptionPane.showMessageDialog(this,"请选择所下载文件的存储位置！",
						"提示",JOptionPane.INFORMATION_MESSAGE);
			}else {
				List<String>datas=new ArrayList<>();
				for(int i=0;i<dataList.size();i++){
					if(dataList.get(i).isSelected)
					datas.add(dataList.get(i).toString());
				}
				if(dataList.size()==0){
					JOptionPane.showMessageDialog(this,"请选择所下载的文件",
							"提示",JOptionPane.INFORMATION_MESSAGE);
					
				}else{
					String url=BFConstants.URL+BFConstants.URLSPE+BFConstants.DOWNLOADFILESURL;
					int flag=downFilesModule.downLoadFile(url, datas, userName, filePath);
					if(flag==200){
						JOptionPane.showMessageDialog(this,"文件下载成功！",
								"提示",JOptionPane.INFORMATION_MESSAGE);
					}else{
						JOptionPane.showMessageDialog(this,"文件下载出现问题！",
								"提示",JOptionPane.INFORMATION_MESSAGE);
						
					}
				}
			}
		}
		
	}
	@Override
	public void mouseClicked(MouseEvent event) {
		// TODO Auto-generated method stub
		  JList list = (JList) event.getSource();
          // Get index of item clicked
          //获得用户点击项的索引
          int index = list.locationToIndex(event.getPoint());
          CheckListItem item = (CheckListItem) list.getModel()
                  .getElementAt(index);
          // 设置列表中项的选择状态
          item.setSelected(!item.isSelected());
          // 重新绘制列表中项
          list.repaint(list.getCellBounds(index, index));
		
	}
	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		first = list.locationToIndex(e.getPoint());
		
	}
	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
//		sec = list.locationToIndex(e.getPoint());
//        if ( sec != -1) {
//            if ( first != sec ) {
//                String s1 = model.getElementAt(first).toString();
//                String s2 = model.getElementAt(sec).toString();
//                model.setElementAt(cli[first], sec);
//                model.setElementAt(cli[sec], first);
//                model.copyInto(cli);
//                list.setModel(model);
//            }
//        }
		
	}
	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
}
